//
//  NetworkingHandler.m
//  UI29_Block
//
//  Created by dllo on 16/1/21.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "NetworkingHandlerOfBlock.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@implementation NetworkingHandler

+ (void)networkingWithUrl:(NSString *)string completeHandle:(void (^)(NSURLResponse *response, NSData *data,id result))block {
    
#pragma mark - 判断网络状态
    
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
        // 将字符串进行转码 (URL 中不能含有中文等字符 )
        
        //NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string]];
        
        /** 方法post */
        
        request.HTTPMethod = @"GET";
        /** body如果是get可为空 */
        
        request.HTTPBody = nil;
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        //
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data) {
                
                
                NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                
                NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetworkingHandler md5HexDigest:string],behind]];
                
                [data writeToFile:path  atomically:YES];
                // NSLog(@"%@", path);
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                // 回到主线程(GCD)
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    block(response, data, result);
                    
                });
                
                
            }
            
        }];
        
        [task resume];
        
        
        
    }else {
        NSLog(@"没有网络(断网)");
        
        NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetworkingHandler md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        //   NSLog(@"%@", data);
        
        if (data == nil) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet" object:nil];
            
            return;
            
        } else {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            block(nil, nil, result);
            
        }
    }
    
}

+ (void)networkingNOSaveWithUrl:(NSString *)string completeHandle:(void (^)(NSURLResponse *, NSData *, id))block {


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string]];
    
    /** 方法post */
    
    request.HTTPMethod = @"GET";
    /** body如果是get可为空 */
    
    request.HTTPBody = nil;
    
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    //
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            
            
            NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
            NSString *behind = @".data";
            NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            
            NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetworkingHandler md5HexDigest:string],behind]];
            
            [data writeToFile:path  atomically:YES];
            // NSLog(@"%@", path);
            // 数据解析
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            // 调用 block
            // 回到主线程(GCD)
            dispatch_async(dispatch_get_main_queue(), ^{
                
                block(response, data, result);
                
            });
            
            
        }
        
    }];
    
    [task resume];


}


/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
    
}




@end
